package com.banksoft.cps.filter;

import com.banksoft.cps.bean.User;
import com.banksoft.cps.constants.WebConstant;
import com.banksoft.cps.enums.UserType;
import com.banksoft.cps.util.CacheUtil;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Created by rongzhao.zhu on 2018/8/30.
 */
public class BuyFilter extends LoginFilter{
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
       /* userService = wac.getBean(UserService.class);*/
    }


    /**
     *
     * @param request
     * @return
     */
    protected User getUser(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if(cookies ==null){
            return null;
        }
        Map<String,String> cookieMap = cookie2map(cookies);
        String token = cookieMap.get(WebConstant.cookieToken);
        User user = CacheUtil.getByKey(token);
        if(user != null  && UserType.buy.name().equals(user.getType())){
            Map<String,String> storedCookie = user.getCookieMap();
            boolean allMatch = storedCookie.entrySet().stream().map(e->e.getValue().equals(cookieMap.get(e.getKey()))).
                    reduce(true,(a,b)->a&&b);
            if(!allMatch){
                return null;
            }else {
                return user;
            }
        }
        return null;
    }

    @Override
    public List<String> getExcludeUri() {
        return excludeUri;
    }

    @Override
    public void setExcludeUri(List<String> excludeUri) {
        this.excludeUri = excludeUri;
    }

    @Override
    public String getLoginUri() {
        return WebConstant.buyLoginUrl;
    }
}
